/* $RCSFile: OrderManager.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ECommerce/PageModules/ECommerce/OrderManager.ascx.cs $
 * $log$
 * Revision 21 2010/08/09 11:08:12  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 8 2010/08/09 10:07:05  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Globalization;
using System.Configuration;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;

using AddonNice.Diagnostics;
using AddonNice.Core;
using AddonNice.Security;
using AddonNice.Configuration;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Settings;
using AddonNice.Helpers;
using AddonNice.Authentication;

using AddonNice.CRMWrapper;

using AddonNice.ECommerce;
using AddonNice.Settings.ECommerce;
using AddonNice.ECommerce.Helpers;
using AddonNice.ECommerce.UI.WebControls;
using AddonNice.CRMWrapper.ECommerce;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.ECommerce
{
	public partial class OrderManager : ECommerceModule 
	{
		private Orders2DB Orders				=	new Orders2DB();


		#region Global Implementation

        public override Guid GuidID 
		{
			get
			{
				return new Guid(EComStStr.OrderManagerGuid);
			}
		}
		
        public override bool DependsFromCustomCrmEntities
        {
            get{ return true;}
        }
        
        /// <summary>
        /// SortedList of entities/version from which this module depends, schema name is the key, version is a string in the form major.minor
        /// </summary>
        public override SortedList<string,string> RelatedCustomEntities
        {
            get
            {
                SortedList<string,string> Lst =   new SortedList<string,string>();
                Lst.Add(EComStStr.adnpayment,"1.0");
                Lst.Add(EComStStr.adngateway,"1.0");
                Lst.Add(EComStStr.adntaxes,"1.0");
                Lst.Add(CrmStr.product,"1.0");
                Lst.Add(CrmStr.salesorder,"1.0");
                Lst.Add(CrmStr.salesorderdetail,"1.0");
                return Lst;
            }
        }

        #endregion Global Implementation

        #region ShoppingCart

        private AddonNiceUser _currentUser = null;
        private AddonNiceUser currentUser
        {
            get
            {
                if (_currentUser == null)
                {
                    _currentUser            =   AddonNiceUser.GetCurrent();
                    if ( (_currentUser == null) || ( portalSettings.AuthMode != AuthenticationMode.Forms ) )
                    {
                        if ( OrderTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager currentUser GET BEG AuthMode: {0}.",portalSettings.AuthMode),OrderTrace.Sw.Info);
                        try
                        {
                                string valGuid  =   Settings[EComStStr.DefaultAccount4Orders].Value.Trim();
                                if ( OrderTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager currentUser GET DefaultAccount4Orders: {0}.",valGuid),OrderTrace.Sw.Info);
                                if ( valGuid == Guid.Empty.ToString() )
                                {
                                    valGuid     =   ADNPage.Settings[EComStStr.PageSettingsDefaultAccount4Orders].Value.Trim();
                                    if ( OrderTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager currentUser GET PageSettingsDefaultAccount4Orders: {0}.",valGuid),OrderTrace.Sw.Info);
                                }
                                if ( valGuid == Guid.Empty.ToString() )
                                {
                                    valGuid     =   portalSettings.CustomSettings[EComStStr.SiteSettingsDefaultAccount4Orders].Value.Trim();
                                    if ( OrderTrace.Sw.TraceVerbose )
                                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager currentUser GET SiteSettingsDefaultAccount4Orders: {0}.",valGuid),OrderTrace.Sw.Info);
                                }
                                Guid accountId  =   new Guid(valGuid);
                                string sellingFrom  =   portalSettings.CustomSettings[EComStStr.SiteSettingsSellingCountry].Value.Trim();
                                _currentUser   =    new EcommerceUser(accountId,sellingFrom);
                        }
                        catch (Exception ex)
                        {
                            if ( OrderTrace.Sw.TraceError )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager currentUser Get ex: {0}", ex),OrderTrace.Sw.Info);
                            throw;
                        }
                    }
                    if ( OrderTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager currentUser Get Key: [{0}],userName: [{1}]",
                             _currentUser.ProviderUserKey, _currentUser.UserName),OrderTrace.Sw.Info);
                }
                if (_currentUser == null)
                {
                    const string msg                =   "[E]OrderManager currentUser is NULL";
                    if ( OrderTrace.Sw.TraceError )
                        Trace2.WriteLine(msg,OrderTrace.Sw.Info);
                    throw new Exception(msg);
                }
                return _currentUser;
            }
        }

        /// <summary>
        /// Take either the current user country or the sellingfrom country
        /// </summary>
        string CountryID
        {
            get
            {
                string sellingFrom  =   currentUser.BillCountryID;
                if ( !string.IsNullOrEmpty(sellingFrom) )
                    sellingFrom  =   portalSettings.CustomSettings[EComStStr.SiteSettingsSellingCountry].Value.Trim();
                return sellingFrom;
            }
        }

        ShoppingCart _Cart  =    null;
        ShoppingCart Cart
        {
            get
            {
                if (_Cart == null)
                {
                    // Try to get current country from user billing country list
                    string country  =   CountryID;
                    // if no set take the selling from country of portal
                    if ( string.IsNullOrEmpty(country) )
                        country     =   portalSettings.CustomSettings[EComStStr.SiteSettingsSellingCountry].ToString();
                    _Cart           =   new ShoppingCart(country,DefaultPriceList,FilterOnPriceList,UseForcedPrice);
                }
                return _Cart;
            }
        }

        /// <summary>
        /// Should we use forced prices in salesorderdetail
        /// </summary>
        public bool UseForcedPrice  
        {
            get
            {
                bool ret    =  portalSettings.CustomSettings[EComStStr.SiteSettingsUseForcedPrices].ToBool();
                if ( !ret )
                    ret     =   ADNPage.Settings[EComStStr.PageSettingsUseForcedPrices].ToBool();
/*                if ( !ret )
                    ret     =    Settings[EComStStr.UseForcedPrices].ToBool();
  */              return ret;
            }
        }

        public bool FilterOnPriceList  
        {
            get
            {
                bool ret    =  portalSettings.CustomSettings[EComStStr.SiteSettingsFilterOnPriceList].ToBool();
                if ( !ret )
                    ret     =   ADNPage.Settings[EComStStr.PageSettingsFilterOnPriceList].ToBool();
/*                if ( !ret )
                    ret     =    Settings[EComStStr.UseForcedPrices].ToBool();
  */              return ret;
            }
        }
       
        /// <summary>
        /// Find Default PriceList which will be used for pricing
        /// Guid.Empty if not defined
        /// </summary>
        Guid _DefaultPriceList   =   Guid.Empty;
        public Guid DefaultPriceList
        {
            get
            {
                if (_DefaultPriceList == Guid.Empty)
                {
                    _DefaultPriceList = PagePriceList;
                }
                if (_DefaultPriceList == Guid.Empty)
                {
                    _DefaultPriceList = PortalPriceList;
                }
                return _DefaultPriceList;
            }
        }

        /*
        /// <summary>
        /// Find Default Module PriceList which will be used for pricing
        /// Guid.Empty if not defined
        /// </summary>
        Guid _ModulePriceList   =   Guid.Empty;
        Guid ModulePriceList
        {
            get
            {
                if ( _ModulePriceList == Guid.Empty )
                {
                    if ( OrderTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( "[V]OrderManager ModulePriceList GET BEG.",OrderTrace.Sw.Info);
                    _ModulePriceList        =   ECommerceHelpers.GetPriceList4CCurrency(EComStStr.ProductPriceList,Settings);
                }
                return _ModulePriceList;
            }
        }
        */

        /// <summary>
        /// Find Default Module PriceList which will be used for pricing
        /// Guid.Empty if not defined
        /// </summary>
        Guid _PagePriceList   =   Guid.Empty;
        Guid PagePriceList
        {
            get
            {
                if ( _PagePriceList == Guid.Empty )
                {
                    if ( OrderTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( "[V]OrderManager PagePriceList GET BEG.",OrderTrace.Sw.Info);
                    _PagePriceList  =   ECommerceHelpers.GetPriceList4CCurrency(EComStStr.PageSettingsPriceList,ADNPage.Settings);
                }
                return _PagePriceList;
            }
        }

        /// <summary>
        /// Find Default Module PriceList which will be used for pricing
        /// Guid.Empty if not defined
        /// </summary>
        Guid _PortalPriceList   =   Guid.Empty;
        Guid PortalPriceList
        {
            get
            {
                if ( _PortalPriceList == Guid.Empty )
                {
                    if ( OrderTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( "[V]OrderManager PortalPriceList GET BEG.",OrderTrace.Sw.Info);
                    _PortalPriceList        =   ECommerceHelpers.GetPriceList4CCurrency(EComStStr.SiteSettingsPriceList,portalSettings.CustomSettings);
                }
                return _PortalPriceList;
            }
        }

        #endregion ShoppingCart

        /// <summary>
        /// Ctor install properties
        /// </summary>
		public OrderManager()
		{
            //const string extgrp                 =   "ORDERMANAGER";
		}

		private Guid mOrderID = Guid.Empty;
		protected Guid OrderID
		{
			get
			{
				if ( mOrderID == Guid.Empty )
				{
					object ob	    =	ViewState[EComStStr.DBOrderID];
					if ( ob != null ) 
						mOrderID    = (Guid)ViewState[EComStStr.DBOrderID];
				}
				return mOrderID;
			}		
			set
			{
				ViewState[EComStStr.DBOrderID]  = value;
				mOrderID                        = value;
			}
		}

		public int GetTheSelectedIndex(int st)
		{
			ListItemCollection Items	=	StatusList;
			ListItem	it				=	Items.FindByValue(st.ToString());
			if ( it == null )
				return -1;
			return Items.IndexOf(it);
		}
		
		public string GetStatus(int st)
		{
			return Order2Helper.GetStatus(st);
		}

		public ListItemCollection StatusList
		{
			get
			{
				return Order2Helper.GetStatusList();
			}
		}

		protected void Page_Load(object sender, System.EventArgs e)
		{
			if ( !IsPostBack ) 
			{
				BindOrders();
				PopulateShoppingCartList();
				}
		}

		void BindOrders()
		{
			// Read list of categories
			SqlDataReader drOrders				=	null;
			DataView dv							=	null;
			ADNPage	p				            =	ADNPage;
			string FilterStr					=	p.Filter;
			string SortStr						=	p.SortOrder;
			try
			{
				DateTime	CreationDate		=	p.QueryDate.ToUniversalTime();
				drOrders						=	Orders.GetAllOrdersFromDate(CreationDate);
				if ( FilterStr != string.Empty )
				{
						DGOrders.AllowCustomPaging	=	false;
						dv							=	CreateDataView(drOrders);
						dv.RowFilter				=	p.Filter;	
						DGOrders.DataSource			=	dv;
						}
				else	
				{
					DGOrders.AllowCustomPaging	=	true;
					dv							=	(DataView)CreateDataSource(drOrders,DGOrders,false);
				}
				if ( p.SortOrder != string.Empty )
					dv.Sort						=	p.SortOrder+" "+p.SortDirection;
				DGOrders.DataBind();

			}
			catch(Exception ex)
			{
                if ( OrderTrace.Sw.TraceError )
    				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager BindOrders ex: {0}",ex),OrderTrace.Sw.Info);
                throw;
			}
			finally
			{
				if ( drOrders != null )
					drOrders.Close();
			}
		}



		private void DGOrders_CancelCommand(object source, DataGridCommandEventArgs e)
		{
			DGOrders.EditItemIndex = -1;
			BindOrders();
		}

		private void DGOrders_EditCommand(object source, DataGridCommandEventArgs e)
		{
			DGOrders.EditItemIndex = e.Item.ItemIndex;
			BindOrders();
		}

		private void DGOrders_UpdateCommand(object source, DataGridCommandEventArgs e)
		{
			Guid	ID				=	Guid.Empty;
			Order2	o				=	new Order2();
			try
			{
				LinkButton lblOrderID	= (LinkButton) e.Item.Cells[2].FindControl("OrderID");
				ID					=	new Guid(lblOrderID.Text);
				o.Load(ID);
				// TD change fields according what has been entered
				DropDownList dl		=	(DropDownList )e.Item.Cells[5].FindControl("DDLStatus");
				o.Status			=	(OrderStatus)(Convert.ToInt32(dl.SelectedValue));
			}
			catch(Exception ex )
			{
                if ( OrderTrace.Sw.TraceError )
    				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager DGOrders_UpdateCommand ex: {0}",ex),OrderTrace.Sw.Info);
				throw;
			}
			try
			{
				Orders.UpdateOrder(o);
			}
			catch(Exception ex )
			{
                if ( OrderTrace.Sw.TraceError )
    				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager DGOrders_UpdateCommand Err DB ex: {0}",ex),OrderTrace.Sw.Info);
				throw;
			}
			DGOrders.EditItemIndex = -1;
			BindOrders();
		}

		private void DGOrders_ItemCreated(object sender, DataGridItemEventArgs e)
		{
			if ( e.Item.ItemType != ListItemType.EditItem )
				return;
			DropDownList l	=	(DropDownList)e.Item.Cells[5].FindControl("DDLStatus");
			if ( l == null )
				return;
			foreach (ListItem Item in StatusList)
				l.Items.Add(Item);
		}

		private void DGOrders_ItemDataBind(object sender, DataGridItemEventArgs e)
		{
			if ( e.Item.ItemType == ListItemType.Footer ||
				e.Item.ItemType == ListItemType.Header ||
				e.Item.ItemType == ListItemType.Pager ||
				e.Item.ItemType == ListItemType.Separator)
				return;
			LinkButton b		    =	(LinkButton )e.Item.Cells[0].Controls[0];
			if ( b == null )
				return;
			LinkButton lblOrderID	=   (LinkButton) e.Item.Cells[2].FindControl("OrderID");
			OrderID					=   new Guid(lblOrderID.Text);
			Order2	o	            =	new Order2();
			try
			{
				o.Load(OrderID);
				switch( o.Status)
				{
					case OrderStatus.ToBeCompleted:
					case OrderStatus.PaymentCompleted:

						Guid PayID	=	o.PaymentID;
						if ( PayID == Guid.Empty )
						{
							b.Text	=	"Create Payment";
							return;
						}
						if ( !o.ExistsShipDemand )
						{
							b.Text	=	"Create Ship Demand";
							return;
						}
						if ( !o.ExistsBill )
						{
							b.Text	=	"Create Bill";
							return;
						}
						break;
				}
			}
			catch(Exception ex )
			{
                if ( OrderTrace.Sw.TraceError )
    				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager DGOrders_SelectedIndexChanged ex: {0}",ex),OrderTrace.Sw.Info);
				throw;
			}
			b.Visible	=	false;
		}

		/// <summary>
		/// When selected check if any shipDemand exists, creates info, check for a bill, create info
		/// </summary>
		protected void DGOrders_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			int idx		            =	DGOrders.SelectedIndex;
			if ( idx == -1 )
				return;
			LinkButton lblOrderID	=   (LinkButton) DGOrders.SelectedItem.Cells[2].FindControl("OrderID");
			OrderID					=   new Guid(lblOrderID.Text);
			Order2	o	            =	new Order2();
			try
			{
				o.Load(OrderID);
				Guid PayID	        =	o.PaymentID;
				if ( PayID == Guid.Empty )
				{
					PayID	        =	o.CreatePayment();
					if ( o.Status != OrderStatus.PaymentCompleted )
					{
						o.Status    = OrderStatus.PaymentCompleted;
						o.Update(null);

					}
				}
				if ( !o.ExistsShipDemand )
					o.GenerateShipDemand();
				if ( !o.ExistsBill )
					o.GenerateBill();
			}
			catch(Exception ex )
			{
                if ( OrderTrace.Sw.TraceError )
    				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager DGOrders_SelectedIndexChanged ex:{0}",ex),OrderTrace.Sw.Info);
				throw;
			}
			BindOrders();
		}

		// Display the order info when clicking the orderID in the orderlist datagrid
		private void OrderList_Command(object sender, DataGridCommandEventArgs e)
		{
			try
			{
				// Display details of a product
				if (e.CommandName == "OrderItemInfo")
				{
					// get the product ID from the invisible cell
					LinkButton lblOrderID	= (LinkButton) e.Item.Cells[2].FindControl("OrderID");
					OrderID					= new Guid(lblOrderID.Text);

					// Display the product 
					DisplayOrderDetails();
				}
			}
			catch (Exception exp)
			{
                if ( OrderTrace.Sw.TraceError )
    				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager OrderList_Command ex: {0}",exp),OrderTrace.Sw.Info);
				lblMessage.Text	=	LocalizeHelper.Localize(EComStStr.ResourceFile,EComStStr.ResourceItem, EComStStr.PRODUCTS_CANNOT_DISPLAY_ORDER,"Cannot display the selected order.");
			}
		}
		
		// Display the parameters of the specified order
		private void DisplayOrderDetails()
		{
			try
			{
				// get orderID
				Guid orderID					=   new Guid(Request.Params["orderid"]);
				// CS 1/3/04 pb displaying order
				if ( orderID == Guid.Empty )
					orderID						=   OrderID;

				// load the order
				Order2 order					=   new Order2();
				order.Load(orderID);
				OrderDetails.Controls.Add(new LiteralControl(order.OrderHtml));

				lblMessage.Text	=	LocalizeHelper.Localize(EComStStr.ResourceFile,EComStStr.ResourceItem, EComStStr.PRODUCTS_DISPLAYING_ORDER,"Displaying order: ") ;
			}
			catch (Exception exp)
			{
                if ( OrderTrace.Sw.TraceError )
    				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager DisplayOrderDetails ex: {0}",exp),OrderTrace.Sw.Info);
				lblMessage.Text	=	LocalizeHelper.Localize(EComStStr.ResourceFile,EComStStr.ResourceItem, EComStStr.PRODUCTS_CANNOT_DISPLAY_ORDER,"Cannot display the selected order.");
			}
		}

		/// <summary>
		/// The UpdateShoppingCartDatabase helper method is used to
		/// update a user's items within the shopping cart database
		/// using client input from the GridControl.
		/// </summary>
		void UpdateShoppingCartDatabase() 
		{
    		if ( OrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager UpdateShoppingCartDatabase RadCarList1.Items.Count: {0}",RadCarList1.Items.Count),OrderTrace.Sw.Info);
			// Iterate through all rows within shopping cart list
			for ( int i=0 ; i < RadCarList1.Items.Count; i++ ) 
			{
				// Obtain references to row's controls
				// Wrap in try/catch block to catch errors in the event that someone types in
				// an invalid value for quantity
				try 
				{
				    string strquantity          =   RadCarList1.Items[i]["Quantity"].Text;
                    if ( OrderTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager UpdateShoppingCartDatabase quantityTxt: {0}",strquantity),OrderTrace.Sw.Info);

					decimal quantity			=   decimal.Parse(strquantity,CultureInfo.InvariantCulture);
					string strProductID			=   RadCarList1.Items[i]["ProductID"].Text;
					string strSavedMetadataXml	=   RadCarList1.Items[i]["SavedMetaDataXml"].Text;
					if ( quantity == 0m || RadCarList1.Items[i].Selected ) 
					{
    		            if ( OrderTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager UpdateShoppingCartDatabase removing lblProductID: {0}",strProductID),OrderTrace.Sw.Info);
						Cart.RemoveItem(new Guid(strProductID), strSavedMetadataXml);
					}
				}
				catch(Exception ex)
				{
    		        if ( OrderTrace.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager UpdateShoppingCartDatabase ex: {0}",ex),OrderTrace.Sw.Info);
                    throw;
				}
			}
		}

		/// <summary>
		/// The PopulateShoppingCartList helper method is used to
		/// dynamically populate a GridControl with the contents of
		/// the current user's shopping cart.
		/// </summary>
		void PopulateShoppingCartList() 
        {
    		if ( OrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]OrderManager PopulateShoppingCartList BEG.",OrderTrace.Sw.Info);
			// Databind Gridcontrol with Shopping CartDB Items
			RadCarList1.DataSource		    =	Cart.GetPricingTable();
			//RadCarList1.DataBind(); PB Telerik with ItemCommand
			
		    // add totals under the grid
			string currencySymbol			=	threeLetterCurrencySymbol;
            string sellingFrom              =   portalSettings.CustomSettings[EComStStr.SiteSettingsSellingCountry].ToString();
	        if ( OrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager PopulateShoppingCartList Total: {0}, discount: {1}",
                    Cart.currentPrice,Cart.discount),OrderTrace.Sw.Info);
			lblTotal.Text					=	new ADNMoney(Cart.currentPrice, currencySymbol).ToString();
			lblTotalDiscount.Text			=	new ADNMoney(Cart.discount, currencySymbol).ToString();
			lblTotalTaxes.Text				=	new ADNMoney(Cart.Taxe, currencySymbol).ToString();
			lblTotalWithTaxes.Text			=	new ADNMoney(Cart.currentPriceWithTaxes, currencySymbol).ToString();
		}

		protected void UpdateCardBtn_Click(object sender, System.EventArgs e)
		{
            if ( OrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager UpdateCardBtn_Click enter at: {0}",DateTime.UtcNow),OrderTrace.Sw.Info);
			try
			{
				// Update the Shopping CartDB and then Repopulate the List
				UpdateShoppingCartDatabase();
				// redisplay the cart
				PopulateShoppingCartList();
                RadCarList1.DataBind(); // BUG Telerik
			}
			catch (Exception exp)
			{
				if ( OrderTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager UpdateCardBtn_Click ex: {0}",exp),OrderTrace.Sw.Info);
				throw;
			}
		}
/*
        void RadCarList1_UpdateCommand(object source, GridCommandEventArgs e)
        {
    		if ( OrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]OrderManager RadCarList1_UpdateCommand BEG.",OrderTrace.Sw.Info);
            try
            {
                GridEditableItem editedItem =   e.Item as GridEditableItem;
                Hashtable newValues         =   new Hashtable();
                editedItem.ExtractValues(newValues);
                object ob                   =   newValues["Quantity"];
    		    if ( OrderTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager RadCarList1_UpdateCommand quantity: {0}.",ob.GetType()),OrderTrace.Sw.Info);
                decimal quantity            =   decimal.Parse((string)ob,CultureInfo.InvariantCulture);
    		    if ( OrderTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager RadCarList1_UpdateCommand quantity: {0}.",quantity),OrderTrace.Sw.Info);
                Guid ProdId                 =   new Guid((string)e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ProductID"]);
			    string strSavedMetadataXml	=   editedItem["SavedMetaDataXml"].Text;
                if ( strSavedMetadataXml == StStr.HTML_SPACE )
                    strSavedMetadataXml     =   string.Empty;
                if (quantity != 0m)
                    Cart.UpdateItem(ProdId, quantity, strSavedMetadataXml);
                else
                    Cart.RemoveItem(ProdId, strSavedMetadataXml);
                PopulateShoppingCartList();
			}
			catch(Exception ex)
			{
		        if ( OrderTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager RadCarList1_UpdateCommand ex: {0}",ex),OrderTrace.Sw.Info);
                throw;
			}
        }
        
 */

        void RadCarList1_DeleteCommand(object source, GridCommandEventArgs e)
        {
            if ( OrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager RadCarList1_DeleteCommand Items: {0}",e.Item),OrderTrace.Sw.Info);
            try
            {
				string strProductID			=   ((GridDataItem)e.Item)[EComStStr.DBProductID].Text;
				string strSavedMetadataXml	=   ((GridDataItem)e.Item)["SavedMetaDataXml"].Text;
                if ( strSavedMetadataXml == StStr.HTML_SPACE )
                    strSavedMetadataXml =   string.Empty;
			    Cart.RemoveItem(new Guid(strProductID), strSavedMetadataXml);
                PopulateShoppingCartList();
			}
			catch(Exception ex)
			{
		        if ( OrderTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager RadCarList1_DeleteCommand ex: {0}",ex),OrderTrace.Sw.Info);
                throw;
			}
        }

		protected void CheckoutBtn_Click(object sender, EventArgs e)
		{
			try
			{
				// Update Shopping CartDB
				UpdateShoppingCartDatabase();
				PopulateShoppingCartList();

				// If cart is not empty, proceed on to checkout page
				// Calculate shopping cart ID
				// If the cart isn't empty, navigate to checkout page
                int nbItems             =   Cart.GetItemCount();
                if ( OrderTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OrderManager CheckoutBtn_Click Nb Items in cart: {0}",nbItems),OrderTrace.Sw.Info);
				if ( nbItems != 0 && Cart.currentPrice != 0m && Cart.currentPriceWithTaxes != 0m )
				{
					RedirectToCheckOut();
				}
				else 
				{
					lblMessage.Text	=	LocalizeHelper.Localize(EComStStr.ResourceFile,EComStStr.ResourceItem,EComStStr.PRODUCT_CHECKOUT_WITH_EMPTY_CART,"Cannot proceed to the Check Out page with an empty cart.");
				}
			}
			catch(System.Threading.ThreadAbortException) 
			{ // nothing it is a response.redirect	
                throw;
			}
			catch (Exception exp)
			{
                if ( OrderTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager CheckoutBtn_Click exp : {0}",exp),OrderTrace.Sw.Info);
                throw;
			}
		}

        // event to build lines of the grid representing the cart
        void RadCarList1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
    		if ( OrderTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Ordermanager RadCarList1_ItemDataBound e: {0}",e.Item.ItemType),OrderTrace.Sw.Info);
			if ( e.Item.ItemType !=  GridItemType.Item 
				&& e.Item.ItemType != GridItemType.AlternatingItem
				&& e.Item.ItemType != GridItemType.SelectedItem)
				return;
			try
			{
				// add the options to the name of the product
				Label lblMetadataXml = (Label)e.Item.FindControl("MetadataXml");
    		    if ( OrderTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Ordermanager RadCarList1_ItemDataBound lblMetadataXml null: {0}",lblMetadataXml == null),OrderTrace.Sw.Info);
				// decode the option string from the metadata
                if ( lblMetadataXml != null )
				    lblMetadataXml.Text = ECommerceHelpers.DecodeOptionsForXsl(lblMetadataXml.Text);
				}
			catch (Exception exp)
			{
                if ( OrderTrace.Sw.TraceError )
    				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Ordermanager CartList_ItemDataBound  e: {0}, ex: {1}",e, exp),OrderTrace.Sw.Info);
				throw;
			}
		}
		
		private void RedirectToCheckOut()
		{
			string checkoutPage =	string.Empty;
			try
			{
				//checkoutPage	=	string.Format("{0}/OrderExternalCheckOut.aspx?Mid={1}&pageid={2}",SecureDirPath,ModuleID,PageID);
				checkoutPage	=	HttpUrlBuilder.BuildUrl("~/OrderExternalCheckOut.aspx",true,DynPageLoc.Secured,PageID,ModuleID,null,string.Empty,string.Empty,string.Empty);
			}
			catch(Exception ex)
			{
                if ( OrderTrace.Sw.TraceError )
    				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OrderManager RedirectToCheckOut SecureDirPath not ok ex: {0}",ex.Message),OrderTrace.Sw.Info);
				return;
			}
			Response.Cache.SetCacheability(HttpCacheability.NoCache);
			//Response.Redirect(checkoutPage);
			ADNPage.Redirect(checkoutPage,true);
		}

		private void DGOrders_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
		{
			DGOrders.CurrentPageIndex	=	e.NewPageIndex;
			BindOrders();
		}

		private void OrderManager_QueryDateChangedEvent(QueryDateChangedEventArgs e)
		{
			BindOrders();
		}

		private void DGOrders_SortCommand(object source, DataGridSortCommandEventArgs e)
		{
			if ( ADNPage.SortOrderList.IndexOf(e.SortExpression) >= 0 )
			{
				ADNPage.SortOrder	=	e.SortExpression;
				BindOrders();
			}
		}

		private void p_SortOrderChangedEvent(SortOrderChangedEventArgs e)
		{

			BindOrders();
		}

		private void p_FilterChangedEvent(FilterChangedEventArgs e)
		{
			BindOrders();
		}

		private void p_PageSizeChangedEvent(PageSizeChangedEventArgs e)
		{
			DGOrders.PageSize	=	e.NewPageSize;
			BindOrders();
		}

		private void p_SortDirectionChangedEvent(SortDirectionChangedEventArgs e)
		{
			BindOrders();
		}
		
        #region Std overrides
		
        override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			ADNPage p	                    =	 ADNPage;
			if ( p != null )
			{
				p.QueryDateChangedEvent	    +=  new QueryDateChangedEventHandler(OrderManager_QueryDateChangedEvent);
				p.SortOrderList	            =	"OrderID;TransacID;DateCreated;DateModified;Status;CustomerID;Name;Email;TotalGoods;TotalTaxes;TotalDiscount;TotalExpenses;TotalShipping;PaymentProvider;ShippingProvider;TotalWeight";
				p.SortOrderChangedEvent	    +=  new SortOrderChangedEventHandler(p_SortOrderChangedEvent);
				p.FilterChangedEvent        +=  new FilterChangedEventHandler(p_FilterChangedEvent);
				p.PageSizeChangedEvent      +=  new PageSizeChangedEventHandler(p_PageSizeChangedEvent);
				p.SortDirectionChangedEvent +=  new SortDirectionChangedEventHandler(p_SortDirectionChangedEvent);
				if ( !p.IsPostBack && DGOrders != null ) 
					p.PageSize	=	DGOrders.PageSize;

			}
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			DGOrders.ItemCreated        +=  new DataGridItemEventHandler(DGOrders_ItemCreated);
			DGOrders.ItemCommand        +=  new DataGridCommandEventHandler(OrderList_Command);
			DGOrders.PageIndexChanged   +=  new DataGridPageChangedEventHandler(DGOrders_PageIndexChanged);
			DGOrders.CancelCommand      +=  new DataGridCommandEventHandler(DGOrders_CancelCommand);
			DGOrders.EditCommand        +=  new DataGridCommandEventHandler(DGOrders_EditCommand);
			DGOrders.SortCommand        +=  new DataGridSortCommandEventHandler(DGOrders_SortCommand);
			DGOrders.UpdateCommand      +=  new DataGridCommandEventHandler(DGOrders_UpdateCommand);
			DGOrders.ItemDataBound      +=  new DataGridItemEventHandler(DGOrders_ItemDataBind);
            RadCarList1.ItemDataBound   +=  new GridItemEventHandler(RadCarList1_ItemDataBound);
            RadCarList1.DeleteCommand   +=  new GridCommandEventHandler(RadCarList1_DeleteCommand);
            //RadCarList1.UpdateCommand   +=  new GridCommandEventHandler(RadCarList1_UpdateCommand);
            UpdateCardBtn.Click         +=  new ImageClickEventHandler(UpdateCardBtn_Click);
            CheckoutBtn.Click           +=  new ImageClickEventHandler(CheckoutBtn_Click);
		}
		#endregion Std overrides
	}
}
